<script setup>
import { ref, watch, onMounted } from "vue";
import {
  queryClazzPageApi,
  addClazzApi,
  queryClazzByIdApi,
  updateClazzApi,
  deleteClazzApi,
  queryClazzAllApi,
} from "@/api/clazz";
import { queryPageApi as queryEmpPageApi } from "@/api/emp";
import { ElMessage, ElMessageBox } from "element-plus";

// 学科下拉
const subjects = [
  { name: "Java", value: 1 },
  { name: "前端", value: 2 },
  { name: "大数据", value: 3 },
  { name: "Python", value: 4 },
  { name: "Go", value: 5 },
  { name: "嵌入式", value: 6 },
];

// 班主任下拉
const masters = ref([]);
const fetchMasters = async () => {
  // 查询所有员工，然后过滤出职位为班主任的员工
  const res = await queryEmpPageApi("", "", "", "", 1, 1000);
  if (res.code) {
    const empList = res.data.records || [];
    masters.value = empList.filter(emp => emp.job === 1);
  }
};

// 查询表单
const searchForm = ref({ name: "", date: [], begin: "", end: "" });
watch(
  () => searchForm.value.date,
  (val) => {
    if (val && val.length === 2) {
      searchForm.value.begin = val[0];
      searchForm.value.end = val[1];
    } else {
      searchForm.value.begin = "";
      searchForm.value.end = "";
    }
  }
);

// 班级列表、分页
const clazzList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

const fetchClazzList = async () => {
  const params = {
    name: searchForm.value.name,
    begin: searchForm.value.begin,
    end: searchForm.value.end,
    page: currentPage.value,
    pageSize: pageSize.value,
  };
  const res = await queryClazzPageApi(params);
  if (res.code) {
    clazzList.value = res.data.records || res.data.list || [];
    total.value = res.data.total;
  }
};

onMounted(() => {
  fetchClazzList();
  fetchMasters();
});

const handleSizeChange = () => fetchClazzList();
const handleCurrentChange = () => fetchClazzList();
const clear = () => {
  searchForm.value = { name: "", date: [], begin: "", end: "" };
  fetchClazzList();
};

// 弹窗表单
const dialogVisible = ref(false);
const dialogTitle = ref("新增班级");
const clazzForm = ref({
  name: "",
  room: "",
  beginDate: "",
  endDate: "",
  masterId: "",
  subject: "",
});
const clazzFormRef = ref();

const openAdd = () => {
  dialogTitle.value = "新增班级";
  dialogVisible.value = true;
  clazzForm.value = {
    name: "",
    room: "",
    beginDate: "",
    endDate: "",
    masterId: "",
    subject: "",
  };
  if (clazzFormRef.value) clazzFormRef.value.resetFields();
};

const openEdit = async (row) => {
  dialogTitle.value = "编辑班级";
  dialogVisible.value = true;
  const res = await queryClazzByIdApi(row.id);
  if (res.code) {
    clazzForm.value = { ...res.data };
  }
};

const saveClazz = () => {
  clazzFormRef.value.validate(async (valid) => {
    if (!valid) return ElMessage.error("表单校验不通过");
    let res;
    if (clazzForm.value.id) {
      res = await updateClazzApi(clazzForm.value);
    } else {
      res = await addClazzApi(clazzForm.value);
    }
    if (res.code) {
      ElMessage.success("保存成功");
      dialogVisible.value = false;
      fetchClazzList();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该班级吗？", "提示", { type: "warning" })
    .then(async () => {
      const res = await deleteClazzApi(row.id);
      if (res.code) {
        ElMessage.success("删除成功");
        fetchClazzList();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

// 表单校验规则
const rules = {
  name: [{ required: true, message: "请输入班级名称", trigger: "blur" }],
  room: [{ required: true, message: "请输入班级教室", trigger: "blur" }],
  beginDate: [{ required: true, message: "请选择开课时间", trigger: "change" }],
  endDate: [{ required: true, message: "请选择结课时间", trigger: "change" }],
  masterId: [{ required: true, message: "请选择班主任", trigger: "change" }],
  subject: [{ required: true, message: "请选择学科", trigger: "change" }],
};
</script>

<template>
  <div>
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline" style="margin-bottom: 16px">
      <el-form-item label="班级名称">
        <el-input v-model="searchForm.name" placeholder="请输入班级名称" clearable />
      </el-form-item>
      <el-form-item label="结课时间区间">
        <el-date-picker
          v-model="searchForm.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchClazzList">查询</el-button>
        <el-button @click="clear">重置</el-button>
      </el-form-item>
      <el-form-item style="float:right; margin-left:auto;">
        <el-button type="primary" @click="openAdd">+ 新增班级</el-button>
      </el-form-item>
    </el-form>

    <!-- 班级表格 -->
    <el-table :data="clazzList" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="name" label="班级名称" />
      <el-table-column prop="room" label="教室" />
      <el-table-column prop="beginDate" label="开课时间" />
      <el-table-column prop="endDate" label="结课时间" />
      <el-table-column prop="masterName" label="班主任" />
      <el-table-column prop="subject" label="学科">
        <template #default="scope">
          {{ subjects.find(s => s.value === scope.row.subject)?.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      :page-sizes="[5, 10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 16px; text-align: right;"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="clazzFormRef?.resetFields()">
      <el-form :model="clazzForm" :rules="rules" ref="clazzFormRef" label-width="100px">
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="clazzForm.name" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="教室" prop="room">
          <el-input v-model="clazzForm.room" placeholder="请输入教室" />
        </el-form-item>
        <el-form-item label="开课时间" prop="beginDate">
          <el-date-picker v-model="clazzForm.beginDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="结课时间" prop="endDate">
          <el-date-picker v-model="clazzForm.endDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="班主任" prop="masterId">
          <el-select v-model="clazzForm.masterId" placeholder="请选择班主任">
            <el-option v-for="emp in masters" :key="emp.id" :label="emp.name" :value="emp.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="学科" prop="subject">
          <el-select v-model="clazzForm.subject" placeholder="请选择学科">
            <el-option v-for="s in subjects" :key="s.value" :label="s.name" :value="s.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveClazz">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
</style>
